package com.hunttown.mes.service;

import com.hunttown.mes.common.cache.Cache;
import com.hunttown.mes.common.keys.KeyConstants;
import com.hunttown.mes.common.utils.FastJsonUtils;
import com.hunttown.mes.common.utils.GeneralUtils;
import com.hunttown.mes.common.utils.ScriptFilterUtils;
import com.hunttown.mes.common.utils.StringUtils;
import com.hunttown.mes.domain.TransportUser;
import com.hunttown.common.domain.Query;
import com.hunttown.mes.dao.LbsTerminalDao;
import com.hunttown.mes.domain.LbsTerminal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

/**
 * created by wangjunfu on 2021-08-31 15:09:13
 */
@Service
public class LbsTerminalService {

    private final static Logger logger = LoggerFactory.getLogger(LbsTerminalService.class);

    private final LbsTerminalDao lbsTerminalDao;
    private final AHelpService helpService;
    private final AnalysisManageService manageService;
    private final TransportUserService userService;
    private final TransportLoginWxService loginWxService;
    private final Cache jedisCache;

    @Autowired
    public LbsTerminalService(LbsTerminalDao lbsTerminalDao, AHelpService helpService, AnalysisManageService manageService, TransportUserService userService, TransportLoginWxService loginWxService, Cache jedisCache) {
        this.lbsTerminalDao = lbsTerminalDao;
        this.helpService = helpService;
        this.manageService = manageService;
        this.userService = userService;
        this.loginWxService = loginWxService;
        this.jedisCache = jedisCache;
    }

    /**
     * 新增
     *
     * @param lbsTerminal 实体对象
     * @return 最新插入id
     */
    public LbsTerminal insert(LbsTerminal lbsTerminal) {
        //api接口传进来是有值的
        if (lbsTerminal.getEntId() == null)
            lbsTerminal.setEntId(helpService.getEnterpriseId());
        if (lbsTerminal.getAdminId() == null)
            lbsTerminal.setAdminId(0);
        if (lbsTerminal.getCreateTime() == null)
            lbsTerminal.setCreateTime(new Date());
        if (lbsTerminal.getStopFlag() == null)
            lbsTerminal.setStopFlag(0);
        if (lbsTerminal.getDeleteFlag() == null)
            lbsTerminal.setDeleteFlag(0);

        if (ScriptFilterUtils.xssFilterForDomain(GeneralUtils.ergodicModel(FastJsonUtils.toJSONString(lbsTerminal), LbsTerminal.class))) {
            return lbsTerminal;
        }
        return lbsTerminalDao.insert(lbsTerminal);
    }

    /**
     * 根据ID修改数据信息
     *
     * @param lbsTerminal 实体对象
     * @return True or False
     */
    public Boolean updateInfoById(LbsTerminal lbsTerminal) {
        if (lbsTerminal.getEntId() == null) {
            lbsTerminal.setEntId(helpService.getEnterpriseId());
        }

        if (ScriptFilterUtils.xssFilterForDomain(GeneralUtils.ergodicModel(FastJsonUtils.toJSONString(lbsTerminal), LbsTerminal.class))) {
            return false;
        }
        return lbsTerminalDao.updateInfoById(lbsTerminal);
    }

    /**
     * 根据Query修改数据信息
     *
     * @param query 需要修改的字段 KV 格式
     * @return True or False
     */
    public Boolean updateInfoByQuery(Query query) {
        if (!query.containsKey("w_entId")) {
            query.put("w_entId", helpService.getEnterpriseId());
        }

        if (ScriptFilterUtils.xssFilterForQuery(query)) {
            return false;
        }
        return lbsTerminalDao.updateInfoByQuery(query);
    }

    /**
     * 根据ID获取记录信息
     *
     * @param id 主键id
     * @return 实体对象
     */
    public LbsTerminal selectById(Integer id) {
        return lbsTerminalDao.selectById(id, helpService.getEnterpriseId());
    }

    /**
     * 根据query取出一条记录，但是可能有多条记录，取最新的一条。
     *
     * @param query 查询条件 KV 格式
     * @return 实体对象
     */
    public LbsTerminal selectObjByQuery(Query query) {
        if (query == null || query.size() == 0) {
            return null;
        }
        if (!query.containsKey("entId")) {
            query.put("entId", helpService.getEnterpriseId());
        }

        List<LbsTerminal> list = selectByQuery(query);
        if (list == null || list.size() == 0) {
            return null;
        }

        return list.get(0);
    }

    //不涉及企业
    public LbsTerminal selectObjWithoutEnt(Query query) {
        if (query == null || query.size() == 0) {
            return null;
        }

        if (!query.containsKey("deleteFlag")) {
            query.put("deleteFlag", 0);
        }

        List<LbsTerminal> list = lbsTerminalDao.selectByQuery(query);
        if (list == null || list.size() == 0) {
            return null;
        }

        return list.get(0);
    }

    /**
     * 根据条件获取List
     *
     * @param query 查询条件 KV 格式
     * @return 实体对象列表
     */
    public List<LbsTerminal> selectByQuery(Query query) {
        if (!query.containsKey("deleteFlag")) {
            query.put("deleteFlag", 0);
        }
        if (!query.containsKey("entId")) {
            query.put("entId", helpService.getEnterpriseId());
        }

        return lbsTerminalDao.selectByQuery(query);
    }

    /**
     * 根据条件获取记录总数
     *
     * @param query 查询条件 KV 格式
     * @return 总记录数
     */
    public Long countByQuery(Query query) {
        if (!query.containsKey("deleteFlag")) {
            query.put("deleteFlag", 0);
        }
        if (!query.containsKey("entId")) {
            query.put("entId", helpService.getEnterpriseId());
        }

        return lbsTerminalDao.countByQuery(query);
    }

    /**
     * 根据ID删除记录信息
     *
     * @param id 主键id
     * @return True or False
     */
    public Boolean deleteById(Integer id) {
        return lbsTerminalDao.deleteById(id, helpService.getEnterpriseId());
    }

    /**
     * 通过终端编码获取数据（先从缓存中获取）
     *
     * @param terminalCode 终端编码
     * @param entId        企业ID
     * @return dto
     */
    public LbsTerminal getByTerminalCodeFromCache(String terminalCode, Integer entId) {
        if (StringUtils.isBlank(terminalCode)) {
            return null;
        }

        LbsTerminal obj = jedisCache.oget(KeyConstants.LBS_TERMINAL_TEMINALCODE + terminalCode + "_" + entId, LbsTerminal.class);
        if (obj == null) {
            obj = getByTerminalCode(terminalCode, entId);
            if (obj != null) {
                jedisCache.oset(KeyConstants.LBS_TERMINAL_TEMINALCODE + terminalCode + "_" + entId, obj);
            }
        }

        return obj;
    }

    // 通过终端编码获取数据
    private LbsTerminal getByTerminalCode(String terminalCode, Integer entId) {
        Query query = Query.noPage();
        query.put("entId", entId);
        query.put("terminalCode", terminalCode);
        query.put("stopFlag", 0);

        return selectObjByQuery(query);
    }

    /**
     * 创建终端，公用（三端通用）
     *
     * @param clientType 1PC/2WXAPP/3H5/4ANDROID/5IOS/6IPAD/7GPS/8POS
     * @param userType   1管理员/2司机/3会员/6车辆
     * @param userId     userType所对应的id都有可能（创建终端时起作用）
     * @param mobile     手机号
     * @param entId      企业ID
     * @return terminal
     */
    public LbsTerminal createTerminal(Integer clientType, Integer userType, Integer userId, String mobile, Integer entId) {

        if (entId == null || entId <= 0) {
            entId = helpService.getEnterpriseId();
        }

        LbsTerminal terminal = new LbsTerminal();
        terminal.setEntId(entId);
        terminal.setServiceId(0);

        if (clientType <= 6) {
            //[1].如果是用户
            terminal.setTerminalType(1);

            int realUserId = userId;
            if (userType == 1) { //管理员
                realUserId = userService.getUseridByManageid(userId, entId);
            }
            if (userType == 2) { //司机
                realUserId = userService.getUseridByDriverid(userId, entId);
            }

            TransportUser user = userService.getFromCacheId(realUserId, entId);
            if (user == null) {
                return null;
            }

            terminal.setTerminalName(user.getTrueName() + "的设备");

            //自购GPS需填写手机号；GBos填写车牌的Base64编码。
            //小程序使用openid；app使用deviceid；其它使用手机号。
            String onlyKey = "";

            if (clientType == 2) { //微信小程序
                onlyKey = loginWxService.getOpenidByRelid(userType, userId, entId);
            }
            if (clientType == 4 || clientType == 5) { //app
                onlyKey = manageService.getDeviceByMobile(user.getMobile(), entId);
            }

            if (StringUtils.isBlank(onlyKey)) { //默认是手机号
                onlyKey = user.getMobile();
            }
            terminal.setTerminalCode(onlyKey);

            terminal.setUserId(realUserId);
            terminal.setCarId(0);

        }

        terminal.setTerminalKey("");
        terminal.setRemark("");
        terminal.setAdminId(0);
        terminal.setCreateTime(new Date());
        terminal.setStopFlag(0);
        terminal.setDeleteFlag(0);
        terminal = insert(terminal);

        return terminal;
    }
}